//
//  QRCodeViewController.swift
//  swift各类控件集锦
//
//  Created by iosdev1 on 2017/5/6.
//  Copyright © 2017年 zyy. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: ZyBaseViewController,AVCaptureMetadataOutputObjectsDelegate {

    var scanLine:UIView? = nil
    var timer:Timer? = nil
    
    var device:AVCaptureDevice? = nil
    var input:AVCaptureDeviceInput? = nil
    var output:AVCaptureMetadataOutput? = nil
    var session:AVCaptureSession? = nil
    var preview:AVCaptureVideoPreviewLayer? = nil
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
//        let bgView = UIView.init(frame: self.view.bounds)
//        self.view.addSubview(bgView)
//        bgView.backgroundColor = UIColor.black
//        bgView.alpha = 0.5
        
        let scanView = UIView.init(frame: CGRect(x:WIDTH_SCREEN/2 - 100, y:HEIGHT_SCREEN/2 - 100, width:200, height:200))
        self.view.addSubview(scanView)
        scanView.layer.masksToBounds = true
        scanView.layer.borderWidth = 1.0
        scanView.layer.borderColor = UIColor.green.cgColor
        
        let lblTitle = UILabel.init(frame: CGRect(x:WIDTH_SCREEN/2 - 100, y:HEIGHT_SCREEN/2 + 150, width:200, height:200))
        self.view.addSubview(lblTitle)
        lblTitle.text = "请把二维码放入扫描框中"

        scanLine = UIView.init(frame: CGRect(x:WIDTH_SCREEN/2 - 100, y:HEIGHT_SCREEN/2 - 100, width:200, height:2))
        scanLine?.backgroundColor = UIColor.red
        self.view.addSubview(scanLine!)
        timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(timerClick), userInfo: "timer", repeats: true)
        
        device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do {
            try input = AVCaptureDeviceInput.init(device: device)
        } catch  {
            echo(data: "错误")
        }
        output = AVCaptureMetadataOutput.init()
        let queue = DispatchQueue.main
        output?.setMetadataObjectsDelegate(self as AVCaptureMetadataOutputObjectsDelegate, queue: queue)
//        限制扫描范围,这个比较特殊参考文档
//        0--1
//        0--WIDTH_SCREEN
//        0--HEIGHT_SCREEN
        
        let rx = (WIDTH_SCREEN/2 - 100)/WIDTH_SCREEN
        let ry = (HEIGHT_SCREEN/2 - 100)/HEIGHT_SCREEN
        let rWidth = 200/WIDTH_SCREEN
        let rHeight = 200/HEIGHT_SCREEN
        output?.rectOfInterest = CGRect(x:rx, y:ry, width:rWidth, height:rHeight)
        
        
        session = AVCaptureSession.init()
        session?.canSetSessionPreset(AVCaptureSessionPresetHigh)
        
        if (session?.canAddInput(input))! {
            session?.addInput(input)
        }
        
        if (session?.canAddOutput(output))! {
            session?.addOutput(output)
        }
        
//        设置条码类型
        output?.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
        
//        添加扫描画面
        preview = AVCaptureVideoPreviewLayer.init(session: session)
        preview?.videoGravity = AVLayerVideoGravityResizeAspectFill
        preview?.frame = self.view.bounds
        self.view.layer.insertSublayer(preview!, at: 0)
//        开始扫描
        session?.startRunning()
    }
    
    func timerClick() {
        UIView.animate(withDuration: 1.5, animations: {
            self.scanLine?.frame = CGRect(x:WIDTH_SCREEN/2 - 100, y:HEIGHT_SCREEN/2 + 100, width:200, height:2)
        }) { (true) in
            self.scanLine?.frame = CGRect(x:WIDTH_SCREEN/2 - 100, y:HEIGHT_SCREEN/2 - 100, width:200, height:2)
        }
    }
    
//    最后实现协议AVCaptureMetadataOutputObjectsDelegate

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        session?.stopRunning()
        if (metadataObjects != nil)&&(metadataObjects.count > 0) {
            let metadata:AVMetadataMachineReadableCodeObject = metadataObjects.first as! AVMetadataMachineReadableCodeObject
            echo(data: "\(metadata.stringValue)")
            DispatchQueue.main.async(execute: { 
                let result = WKWebViewController()
                result.url = metadata.stringValue
                self.navigationController?.pushViewController(result, animated: true)
            })
        }
    }
    
    

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
